import { Breadcrumb, Table, message, Row, Col, Input, Button, Modal, Space } from 'antd';
import React, { FC } from 'react';
import { Utils, FormPanel, FormPanelBtnDisplay, FormPanelBtnAlign, FormPanelObject, InputType } from 'lfun-bg-comp';
import _ from 'lodash';
import { PageContainer } from '@/component/page-container';
import { PAGINATIONCONFIG } from '@/constant/page';
import { createSubject, delSubject, searchSubject, updateSubject } from '@/service/unit/course';
import styles from './index.less';
import { getCourseOptions, getGradeOptions } from '@/service/options';
import { SUBJECT_LEVEL, TEACH_METHOD } from '@/constant/schoolOptions';
import { get_stoge_pz, set_stoge_pz } from '@/utils';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';

const Groups: FC = () => {
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [search, setSearch] = React.useState('');
  const [showNewModel, setShowNewModel] = React.useState(false);
  const [showNewKbModel, setShowNewKbModel] = React.useState(false);
  const [showEditModel, setShowEditModel] = React.useState(false);
  const [showUpdateKbModel, setShowUpdateKbModel] = React.useState(false);
  const [subject, setSubject] = React.useState({});

  const [dataSource, setDataSource] = React.useState([]);

  const searchFunc = async (pageIndex, pageSize) => {
    const res = await searchSubject(Utils.getProps('schoolInfo')?.school_id, search, pageIndex, pageSize);
    if (res.success) {
      setDataSource(res.data.items);
      setTotal(res.data.total);
      setPageIndex(pageIndex);
      setPageSize(pageSize);
    }
  };

  React.useEffect(() => {
    searchFunc(pageIndex, pageSize);
  }, []);

  const pageChange = (pageIndex, pageSize) => {
    set_stoge_pz(pageSize);
    searchFunc(pageIndex, pageSize);
  };
  const columns = [
    {
      title: '编号',
      dataIndex: 'index',
      key: 'index',
      width: 100,
      render: (text, record, index) => index + 1, // 序号从 1 开始
    },
    {
      title: '课程',
      dataIndex: 'subject_name',
      key: 'subject_name',
      width: 200,
    },
    {
      title: '学科',
      dataIndex: 'course_name',
      key: 'course_name',
      width: 200,
    },
    {
      title: '课程等级',
      dataIndex: 'subject_level',
      key: 'subject_level',
      width: 200,
      render: (text: any, record: any) => {
        if (!text) return '';
        return _.find(SUBJECT_LEVEL, { value: text })?.label;
      },
    },
    {
      title: '操作',
      dataIndex: 'selected',
      key: 'selected',
      //width: 100,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text: any, record: any) => {
        return (
          <Space>
            <PermissionButton permission="edit">
              <Button
                type="link"
                onClick={() => {
                  if (record.subject_level !== 'none') {
                    setShowUpdateKbModel(true);
                  } else setShowEditModel(true);
                  setSubject(record);
                }}
              >
                编辑
              </Button>
            </PermissionButton>
            <PermissionButton permission="delete">
              <Button
                type="link"
                onClick={() => {
                  Modal.confirm({
                    title: '删除',
                    content: `是否删除课程${record.subject_name}?`,
                    onOk: async () => {
                      const r = await delSubject(record.id);
                      if (r.success) {
                        searchFunc(pageIndex, pageSize);
                        message.success('操作成功');
                      } else {
                        message.error(r.message || r.details);
                      }
                    },
                  });
                }}
              >
                删除
              </Button>
            </PermissionButton>
          </Space>
        );
      },
    },
  ];

  const xkTemplate = [
    {
      title: '',
      span: 24,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          name: 'subject_name',
          key: 'subject_name',
          label: '课程名称',
          required: true,
        },
        {
          name: 'course_no',
          label: '学科',
          key: 'course_no',
          inputType: InputType.select,
          renderOption: getCourseOptions,
        },
        {
          name: 'subject_alias',
          key: 'subject_alias',
          label: '课程别称',
        },
        {
          label: '所属年级',
          name: 'grade_id',
          key: 'grade_id',
          required: true,
          inputType: InputType.select,
          renderOption: getGradeOptions,
          formatValue: (value: any) => {
            if (!value) return '';
            return `${value}`;
          },
        },
      ],
    },
  ];
  const xbTemplate = [
    {
      title: '',
      span: 24,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '课程名称',
          name: 'subject_name',
          key: 'subject_name',
          required: true,
        },
        {
          label: '课程等级',
          name: 'subject_level',
          key: 'subject_level',
          required: true,
          inputType: InputType.select,
          renderOption: SUBJECT_LEVEL,
        },
        {
          label: '课程别名',
          name: 'subject_alias',
          key: 'subject_alias',
        },
        {
          label: '所属年级',
          name: 'grade_id',
          key: 'grade_id',
          required: true,
          inputType: InputType.select,
          renderOption: getGradeOptions,
          formatValue: (value: any) => {
            if (!value) return '';
            return `${value}`;
          },
        },
        {
          label: '课程简介',
          name: 'subject_description',
          key: 'subject_description',
          inputType: InputType.textarea,
        },
        {
          label: '课程要求',
          name: 'subject_requirement',
          key: 'subject_requirement',
          inputType: InputType.textarea,
        },
        {
          label: '总学时',
          name: 'credit_hour',
          key: 'credit_hour',
          inputType: InputType.number,
        },
        {
          label: '周学时',
          name: 'week_credit_hour',
          key: 'week_credit_hour',
          inputType: InputType.number,
        },
        {
          label: '自学学时',
          name: 'self_study_credit_hour',
          key: 'self_study_credit_hour',
          inputType: InputType.number,
        },
        {
          label: '授课方式代码',
          name: 'teach_method',
          key: 'teach_method',
          inputType: InputType.select,
          renderOption: TEACH_METHOD,
        },
        {
          label: '教材编码',
          name: 'textbook_code',
          key: 'textbook_code',
        },
        {
          label: '参考书目录',
          name: 'reference_book',
          key: 'reference_book',
        },
      ],
    },
  ];

  return (
    <PageContainer header={<Breadcrumb items={[{ title: '课程管理' }]} />}>
      <Row className={styles.search_view}>
        <Col span={24}>
          <Space>
            <Input
              allowClear
              className={styles.search_input}
              placeholder="请输入关键词"
              value={search}
              onChange={e => setSearch(e?.target?.value)}
            />
            <Button
              type="primary"
              onClick={() => {
                searchFunc(pageIndex, pageSize);
              }}
              className={styles.search_btn}
            >
              搜索
            </Button>
            <PermissionButton permission="create_subject">
              <Button type="primary" onClick={() => setShowNewModel(true)}>
                创建学科课程
              </Button>
            </PermissionButton>
            <PermissionButton permission="create_textbook">
              <Button type="primary" onClick={() => setShowNewKbModel(true)}>
                创建校本课程
              </Button>
            </PermissionButton>
          </Space>
        </Col>
        <Col span={24} style={{ marginTop: 20 }}>
          <Table
            columns={columns}
            dataSource={dataSource}
            scroll={{ x: 'max-content' }}
            pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
          />
        </Col>
      </Row>
      <Modal width="50%" title="创建学科课程" footer={[]} open={showNewModel} onCancel={() => setShowNewModel(false)}>
        <FormPanel
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="取消"
          submitBtnText="提交"
          onReset={() => setShowNewModel(false)}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            values.school_id = Utils.getProps('schoolInfo')?.school_id;
            values.subject_level = 'none';
            const res = await createSubject(values);
            if (res.success) {
              message.success('添加成功');
              setShowNewModel(false);
              searchFunc(pageIndex, pageSize);
              formPanelObject.resetFields();
            } else {
              formPanelObject.reVaildation(res);
            }
            return false;
          }}
          template={xkTemplate}
        />
      </Modal>
      <Modal
        width="50%"
        title="创建课本课程"
        footer={[]}
        open={showNewKbModel}
        onCancel={() => setShowNewKbModel(false)}
      >
        <FormPanel
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="取消"
          submitBtnText="提交"
          onReset={() => setShowNewKbModel(false)}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            values.school_id = Utils.getProps('schoolInfo')?.school_id;
            const res = await createSubject(values);
            if (res.success) {
              message.success('添加成功');
              setShowNewKbModel(false);
              searchFunc(pageIndex, pageSize);
              formPanelObject.resetFields();
            } else {
              formPanelObject.reVaildation(res);
            }
            return false;
          }}
          template={xbTemplate}
        />
      </Modal>
      <Modal width="50%" title="编辑学科课程" footer={[]} open={showEditModel} onCancel={() => setShowEditModel(false)}>
        <FormPanel
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="取消"
          submitBtnText="提交"
          values={subject}
          onReset={() => setShowEditModel(false)}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            const res = await updateSubject({ ...subject, ...values });
            if (res.success) {
              message.success('编辑成功');
              setShowEditModel(false);
              searchFunc(pageIndex, pageSize);
              formPanelObject.resetFields();
            } else {
              formPanelObject.reVaildation(res);
            }
            return false;
          }}
          template={xkTemplate}
        />
      </Modal>
      <Modal
        width="50%"
        title="编辑课本课程"
        footer={[]}
        open={showUpdateKbModel}
        onCancel={() => setShowUpdateKbModel(false)}
      >
        <FormPanel
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="取消"
          submitBtnText="提交"
          values={subject}
          onReset={() => setShowUpdateKbModel(false)}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            const res = await updateSubject({ ...subject, ...values });
            if (res.success) {
              message.success('编辑成功');
              setShowUpdateKbModel(false);
              searchFunc(pageIndex, pageSize);
              formPanelObject.resetFields();
            } else {
              formPanelObject.reVaildation(res);
            }
            return false;
          }}
          template={xbTemplate}
        />
      </Modal>
    </PageContainer>
  );
};

export default Groups;
